package com.jqsoft.launcher.util;

import android.content.Context;
import android.util.Log;

import com.jqsoft.launcher.common.Constant;

import org.apache.commons.lang.StringUtils;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by Administrator on 2017-12-04.
 */

public class EcgUtil {
    public static short[] mergeShortArrayList(List<short[]> list) {
        if (list == null || list.size() == 0) {
            return null;
        } else {
            int totalLength = 0;
            for (int i = 0; i < list.size(); ++i) {
                short[] src = list.get(i);
                totalLength += src.length;
            }
            short[] dst = new short[totalLength];
            int pos = 0;
            for (int i = 0; i < list.size(); ++i) {
                short[] src = list.get(i);
                System.arraycopy(src, 0, dst, pos, src.length);
                pos += src.length;
            }
            return dst;
        }
    }

    public static String getSavedFilePath(Context ctx, String dstFileName) {
        String fullPath = getSavedPath(ctx) + "/" + dstFileName;
        File file = new File(fullPath);
        boolean isFileExist = file.exists();
        try {
            if (!isFileExist) {
                file.createNewFile();
            }
        } catch (Exception e) {
            fullPath = null;
        }
        return fullPath;
    }

    //    public static short[] readShortArrayFromFileName(Context ctx, String fileName){
//        String fullPath = getSavedFilePath(ctx, fileName);
//
//    }
    public static boolean writeBytesToFileName(Context ctx, String fileName, byte[] buffer) {
        if (StringUtils.isBlank(fileName)) {
            return false;
        }
        String dirPath = getSavedPath(ctx) + "/";
        String fullPath = dirPath + fileName;
        File file = new File(fullPath);
        boolean isFileExist = file.exists();
        try {
            if (!isFileExist) {
                file.createNewFile();
            } else {
                file = recreateFile(file);
//                File to = new File(file.getAbsolutePath()+System.currentTimeMillis());
//                file.renameTo(to);
//                to.delete();
//                file=new File(fullPath);
//                file.createNewFile();
            }
            saveEcgFile(ctx, file, buffer);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static boolean writeShortArrayToFileName(Context ctx, String fileName, short[] buffer) {
        if (StringUtils.isBlank(fileName)) {
            return false;
        }
        String dirPath = getSavedPath(ctx) + "/";
        String fullPath = dirPath + fileName;
        File file = new File(fullPath);
        boolean isFileExist = file.exists();
        try {
            if (!isFileExist) {
                file.createNewFile();
            } else {
                file = recreateFile(file);
//                File to = new File(file.getAbsolutePath()+System.currentTimeMillis());
//                file.renameTo(to);
//                to.delete();
//                file=new File(fullPath);
//                file.createNewFile();
            }
            saveShortArrayEcgDataToFile(ctx, file, buffer);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static File recreateFile(File file) throws NullPointerException,IOException {
        String fullPath = file.getAbsolutePath();
        File to = new File(fullPath + System.currentTimeMillis());
        file.renameTo(to);
        to.delete();

        File newFile = new File(fullPath);
        newFile.createNewFile();

        return newFile;

    }

    public static void writeInputStreamToFile(InputStream is, File file) throws IOException {
        FileOutputStream fos = null;
        try {
            byte[] data = new byte[2048];
            int nbread = 0;
            fos = new FileOutputStream(file);
            while ((nbread = is.read(data)) > -1) {
                fos.write(data, 0, nbread);
            }
        } catch (Exception ex) {
            Log.d("Exception", ex.toString());
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

//    public static void main(Context ctx, String[] args) {
//        //读取心电文件
//        byte[] ecgData = readEcgFile(ctx, "ecg/1512273450926_data.dat");
////        String s  = new String(Base64.encode(ecgData1));
////        String ss = Base64.base64Decode(s);
////        byte[] ecgData = ss.getBytes();
//
//
//        if (ecgData == null){
//            return;
//        }
//        int frameSize = 12000;// 1帧 1导是500个点 一个点是short 两个字节      所以12导    500 * 2 * 12 = 12000
//        List<Map<String, byte[]>> result = null;
//        int j = ecgData.length / frameSize;//计算出帧
//
//
//        List<GStrongFrameECGGt1000Data> frames = new ArrayList<>(j);
//        for (int i = 0; i < j; i++) {
//            GStrongFrameECGGt1000Data frame = new GStrongFrameECGGt1000Data();
//            frame.decode(ecgData, frameSize * i, frameSize);
//            frames.add(frame);
//        }
//
//        //将心电数据转化为图片
//        EcgGt1000DataDrawer jpgPainter = new EcgGt1000DataDrawer((byte) 2);
//        result = jpgPainter.buildPicture(frames);
//
//        for (int i = 1; i <= result.size(); i++) {
//            Map<String, byte[]> frameData = result.get(i - 1);
//            for (Map.Entry<String, byte[]> entry : frameData.entrySet()) {
//                // 心电图片路径
//                String picturePathName = entry.getKey() + ".jpg";
//                saveEcgFile(ctx, picturePathName, entry.getValue());
//            }
//        }
//    }


    public static byte[] readEcgFile(Context ctx, String name) {
        if (name == null) {
            return null;
        }
//        File file = new File(path);
//        if (!file.exists()){
//            return null;
//        }

        byte[] result = null;
        InputStream inputStream = null;
//        FileInputStream inputStream = null;
        try {

            inputStream = ctx.getAssets().open(name);

//            inputStream = new FileInputStream(is);
            result = new byte[inputStream.available()];
            inputStream.read(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;

    }

    public static void saveShortArrayEcgDataToFile(Context ctx, File file, short[] buffer) {
        try {
            FileOutputStream osFile = new FileOutputStream(file);
            BufferedOutputStream osBuffer = new BufferedOutputStream(osFile, 1024 * 1024);
            DataOutputStream osWriter = new DataOutputStream(osBuffer);
            for (short s : buffer) {
                osWriter.writeShort(s);
            }
            osWriter.close();
            osBuffer.close();
            osFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void saveEcgFile(Context ctx, File file, byte[] buff) throws IOException {
//        if (name == null || buff == null){
//            return ;
//        }
//        String fullPath = getSavedPath(ctx)+"/"+name;
//        File file = new File(fullPath);
        BufferedOutputStream outputStream = null;
        FileOutputStream fos = null;
//        try {
        fos = new FileOutputStream(file);
        outputStream = new BufferedOutputStream(fos);
        outputStream.write(buff);
        outputStream.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }finally {
        if (outputStream != null) {
//                try {
            outputStream.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
        }
//            if (fos!=null){
//                try {
//                    fos.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
    }

    public static String getSavedPath(Context ctx) {
        //判断是否存在sd卡
        boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
        String dbDir = "";
//        sdExist=false;
        if (!sdExist) {//如果不存在,
            Log.e("SD卡管理：", "SD卡不存在，请加载SD卡");
            dbDir = getInnerStoragePath(ctx);
        } else {//如果存在
            //获取sd卡路径
//            dbDir = android.os.Environment.getExternalStorageDirectory().toString();
            dbDir = ctx.getExternalFilesDir("").getAbsolutePath();
        }
        String packageName = ctx.getPackageName();
        dbDir += Constant.ECG_DATA_DIR;//数据库所在目录

        File file = new File(dbDir);
        if (!file.exists()) {
            file.mkdirs();
        }

        return dbDir;

    }

    public static String getInnerStoragePath(Context ctx) {
        String s = ctx.getFilesDir().getAbsolutePath();
        return s;
    }

}
